package rsj.api.org.importdata.entity;

import com.rlyy.aibase.db.Dbink;
import com.rlyy.aibase.utils.base.Node;
import com.rlyy.aibase.utils.base.ThinkException;
import common.exec.RsjIllegalArgueException;
import common.util.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import rsj.api.org.entity.ImportFailedReason;
import rsj.api.org.entity.ImportTestDataEntity;
import rsj.api.org.entity.UploadFileParam;
import rsj.db.PostgresqlConn;
import rsj.db.dbutils.UniqueID;
import common.util.QueryRunnerFactory;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * 执行导入测试数据sql
 *
 * @author yuanqinglong
 * @since 2021/3/4 17:34
 */
@Component
public class ExecutionImportTestData {

    private static final Logger logger = LoggerFactory.getLogger(ExecutionImportTestData.class);


    /**
     * 保存导入解析成功和失败的数据
     *
     * @param importTestDataEntity 解析成功的数据
     * @param importFailedReasons  解析失败的数据
     * @param uploadFileParam      请求参数
     */
    public void addImportFailedAndSuccessfullyData(List<ImportTestDataEntity> importTestDataEntity, List<ImportFailedReason> importFailedReasons,
                                                   UploadFileParam uploadFileParam) {
        this.addSuccessData(importTestDataEntity, uploadFileParam.getOrgId());
        this.addFailedData(importFailedReasons, uploadFileParam.getOrgId());
    }


    /**
     * 执行导入解析成功的数据
     *
     * @param importTestDataEntity 数据
     */
    private void addSuccessData(List<ImportTestDataEntity> importTestDataEntity, String orgId) {
        if (CollectionUtils.isEmpty(importTestDataEntity)) {
            return;
        }
        String sql = assemblyTestLogSql(importTestDataEntity, orgId);
        Connection connection = PostgresqlConn.getConnection();
        try {
            int update = QueryRunnerFactory.getQueryRunner().update(connection, sql);
            logger.info("机构管理-添加导入测试数据成功：{}", update);
        } catch (SQLException e) {
            logger.error("机构管理-添加导入测试数据失败,SQL:{}", sql, e);
            throw new RsjIllegalArgueException("添加导入测试数据失败");
        } finally {
            Dbink.close(connection);
        }

    }


    /**
     * 组装测试日志sql
     *
     * @param importTestDataEntity 导入数据
     * @param orgId                机构id
     * @return sql
     */
    public static String assemblyTestLogSql(List<ImportTestDataEntity> importTestDataEntity, String orgId) {
        String sql = " INSERT INTO sys.oper_test_log (log_id, log_user_id, log_orgp_id, log_ip, log_reqtime, log_reqsernumber, " +
                " log_prod_uid, log_iscost, log_dsname, log_dsreqtime, log_dsnumber, log_dscost, log_storagetime) " +
                " VALUES ";
        String uniqueIdentifier = queryCallerUniqueIdentifier(orgId);
        Assert.isNotBlank(uniqueIdentifier, "查询机构调用者唯一标识不存在");
        StringBuilder values = new StringBuilder();
        for (int i = 0; i < importTestDataEntity.size(); i++) {
            ImportTestDataEntity dataEntity = importTestDataEntity.get(i);
            if (i > 0) {
                values.append(",");
            }
            values.append("(")
                    .append("'").append(UniqueID.generateId()).append("'").append(",")
                    .append("'").append(uniqueIdentifier).append("'").append(",")
                    .append("'").append(dataEntity.getLogOrgpId()).append("'").append(",")
                    .append("'").append(dataEntity.getLogIp()).append("'").append(",")
                    .append("'").append(dataEntity.getLogReqtime()).append("'").append(",")
                    .append("'").append(dataEntity.getLogReqsernumber()).append("'").append(",")
                    .append("'").append(dataEntity.getLogProdUid()).append("'").append(",")
                    .append("'").append(dataEntity.getLogIscost()).append("'").append(",")
                    .append("'").append(dataEntity.getLogDsname()).append("'").append(",")
                    .append("'").append(dataEntity.getLogDsreqtime()).append("'").append(",")
                    .append("'").append(dataEntity.getLogDsnumber()).append("'").append(",")
                    .append("'").append(dataEntity.getLogDscost()).append("'").append(",")
                    .append("'").append(dataEntity.getLogStoragetime()).append("'")
                    .append(")");
        }
        return sql + values.toString();
    }


    /**
     * 查询机构调用者唯一标识
     *
     * @param orgId 机构id
     * @return 唯一标识
     */
    private static String queryCallerUniqueIdentifier(String orgId) {
        Connection connection = PostgresqlConn.getConnection();
        String sql = "SELECT aut_keyid FROM sys.sys_org org LEFT JOIN sys.sys_authon au ON au.aut_org_id = org.org_id WHERE org_id = '" + orgId + "'";
        Node node;
        try {
            node = QueryRunnerFactory.getQueryRunner().queryLinkNode(connection, sql);
        } catch (ThinkException e) {
            throw new RsjIllegalArgueException("机构调用者唯一标识失败");
        } finally {
            Dbink.close(connection);
        }
        return node.value();
    }


    /**
     * 执行导入解析失败的数据
     *
     * @param importFailedReasons 数据
     */
    private void addFailedData(List<ImportFailedReason> importFailedReasons, String orgId) {
        if (CollectionUtils.isEmpty(importFailedReasons)) {
            return;
        }
        String sql = " INSERT INTO sys.oper_test_fail_log(log_id, log_reqsernumber,log_content, log_fail_res, log_is_ignore, log_storagetime,log_org_id) VALUES ";
        StringBuilder values = new StringBuilder();
        for (int i = 0; i < importFailedReasons.size(); i++) {
            ImportFailedReason dataEntity = importFailedReasons.get(i);
            if (i > 0) {
                values.append(",");
            }
            values.append("(")
                    .append("'").append(UniqueID.generateId()).append("'").append(",")
                    .append("'").append(dataEntity.getLogReqsernumber()).append("'").append(",")
                    .append("'").append(dataEntity.getLogContent()).append("'").append(",")
                    .append("'").append(dataEntity.getLogFailRes()).append("'").append(",")
                    .append("'").append(dataEntity.getLogIsIgnore()).append("'").append(",")
                    .append("'").append(dataEntity.getLogStoragetime()).append("'").append(",")
                    .append("'").append(orgId).append("'")
                    .append(")");
        }
        Connection connection = PostgresqlConn.getConnection();
        try {
            QueryRunnerFactory.getQueryRunner().update(connection, sql + values);
        } catch (SQLException e) {
            logger.error("添加导入测试数据失败,SQL:{}", sql, e);
            throw new RsjIllegalArgueException("添加导入测试数据失败");
        } finally {
            Dbink.close(connection);
        }

    }


}
